/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package basecontrollcenter.elements;

import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import javax.swing.JLabel;

/**
 *
 * @author rbs
 */
public final class AutoSizeLabel extends JLabel{

    public AutoSizeLabel(){
        new AutoSizeLabel("");
    }
    
    public AutoSizeLabel(String text) {
    
        super (text);
        AutoResizeText();
        
        addComponentListener(new ComponentListener() {

            @Override
            public void componentResized(ComponentEvent e) {
                AutoResizeText();
            }
            @Override
            public void componentMoved(ComponentEvent e) {}
            @Override
            public void componentShown(ComponentEvent e) {}
            @Override
            public void componentHidden(ComponentEvent e) {}
        });
        
        
    }
    
    public final void center()
    {
        setHorizontalAlignment(JLabel.CENTER);
    }
    
    public final void AutoResizeText()
    {
        if ( !(getText().isEmpty() || getHeight() == 0 || getWidth() == 0))
        {
                int stringWidth;
                FontMetrics metric;       
                int size = 8;
                
                do {
                    Font font = new Font(getFont().getName(), getFont().getStyle(), size);
                    metric = getFontMetrics(font);
                    stringWidth = metric.stringWidth(getText());
                    size ++;
                } while(stringWidth < (getWidth() -5) && metric.getHeight() < (getHeight() -5 ));
                
                setFont(new Font(getFont().getName(), getFont().getStyle(), size - 2));
        }
    }

    

    
}
